package user

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/dto/user_dto"
	userRepo "git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/repository/base/user"
	baseUserPb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/base/user/user_service"
	"git.myscrm.cn/golang/stark/v4"
)

type userNewService struct {
	userNewRepo userRepo.UserNewRepositoryIface
}

func NewUserNewService(userNewRepo userRepo.UserNewRepositoryIface) UserNewServiceIface {
	return &userNewService{userNewRepo: userNewRepo}
}

// SyncUserByJm 同步建模用户数据到新表
func (s *userNewService) SyncUserByJm(ctx context.Context, operation string, userList []user_service.IncrUserInfo) (bool, error) {
	request := baseUserPb.BaseOldUserSyncRequest{
		Users: []*baseUserPb.BaseOldUser{},
		Op:    operation,
	}
	// 构建
	for _, v := range userList {
		status := 1
		if v.IsDisable {
			status = 2
		}
		item := &baseUserPb.BaseOldUser{
			Uid:                 v.UserGuid,
			Account:             v.UserCode,
			Name:                v.UserName,
			Mobile:              v.MobilePhone,
			Email:               v.Email,
			Position:            v.Position,
			Salt:                v.Salt,
			Password:            v.Password,
			Source:              3, // 建模导入或者更新的，默认为 3
			Status:              int32(status),
			LastSetPasswordTime: v.PasswordModifyTime,
			CreatedOn:           v.CreatedTime,
			ModifiedOn:          v.ModifiedTime,
			OrganizationUid:     v.BuGuid,
		}
		request.Users = append(request.Users, item)
	}
	_, err := s.userNewRepo.SyncUsers(ctx, &request)
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncUsers err:%+v", err)
		return false, err
	}
	return true, nil
}

func (s *userNewService) GetAllUserWithOrganization(ctx context.Context) (*user_dto.OrganizationWithUserDto, error) {
	data, err := s.userNewRepo.GetAllUserWithOrganization(ctx)
	if err != nil {
		return nil, err
	}
	if data == nil {
		return nil, errors.New("获取用户列表失败")
	}
	return setSliceToZero(data.RootOrg), nil
}

func setSliceToZero(orgWithUser *baseUserPb.OrganizationWithUser) *user_dto.OrganizationWithUserDto {
	if orgWithUser == nil {
		return nil
	}
	orgWithUserDto := &user_dto.OrganizationWithUserDto{
		OrgId:    orgWithUser.Id,
		OrgName:  orgWithUser.OrgName,
		Users:    []*user_dto.UserMiniInfoDto{},
		ChildOrg: []*user_dto.OrganizationWithUserDto{},
	}
	for _, user := range orgWithUser.Users {
		orgWithUserDto.Users = append(orgWithUserDto.Users, &user_dto.UserMiniInfoDto{
			Id:     user.Id,
			Name:   user.Name,
			Mobile: user.Mobile,
		})
	}

	for _, childOrg := range orgWithUser.ChildOrg {
		orgWithUserDto.ChildOrg = append(orgWithUserDto.ChildOrg, setSliceToZero(childOrg))
	}
	return orgWithUserDto
}

// GetAllUserList 获取全量用户
func (s *userNewService) GetAllUserList(ctx context.Context) (*user_dto.GetAllUserResponse, error) {
	data, err := s.userNewRepo.GetAllUserList(ctx)
	if err != nil {
		return nil, err
	}
	resp := &user_dto.GetAllUserResponse{
		Total: 0,
		List:  []*user_dto.GetAllUserItem{},
	}
	if data != nil {
		resp.Total = data.Total
		for _, item := range data.List {
			resp.List = append(resp.List, &user_dto.GetAllUserItem{
				Id:       item.Id,
				UserName: item.UserName,
				Uid:      item.Uid,
			})
		}

	}
	return resp, nil
}
